<?php 
if(!isset($_SESSION['Username'])) require('sessionStart.php');


if($_SESSION['group'] != 'Guest') {

	include('connect.php');
	$result = mysql_query("SELECT * FROM IMAGES");
	if(mysql_num_rows($result) == 0)
		echo('<br/><div class="h1">No Images on Record! </div><br/>');
	else{
		echo('<br/><div class="h1">Stored Images: </div><br/>');
		printTable($result);
		echo('<br/><br/>');
	}
	include('disconnect.php');

	if(isset($_FILES["file"]["error"])){
		if (($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg")	// jpeg for Firefox
			|| ($_FILES["file"]["type"] == "image/pjpeg")	// pjpeg for Internet Explorer
			|| ($_FILES["file"]["type"] == "image/png"))
		{	
			if ($_FILES["file"]["error"] > 0){
				echo ('File upload error: Error Code: '.$_FILES["file"]["error"].'<br />');
			}
			else{
				/*
				File name = $_FILES["file"]["name"]
				File type = $_FILES["file"]["type"]
				File size = $_FILES["file"]["size"]
				Temporary file name = $_FILES["file"]["tmp_name"]
				*/
				if (file_exists("../images/" . $_FILES["file"]["name"])){
					echo('A file of the name '.$_FILES["file"]["name"].' already exists.'.$_FILES["file"]["name"]);
				}
				else{
					//STORE THE UPLOADED IMAGE IN THE IMAGES FOLDER
					move_uploaded_file($_FILES["file"]["tmp_name"],
					"../images/" . $_FILES["file"]["name"]);
					echo ('The file '.$_FILES["file"]["name"].' has been saved successfully.'.$_FILES["file"]["name"]);
					
					// STORE IMAGE INFO IN DATABASE
					include('connect.php');
					if(isset($_POST['description'])){
						$query = ('insert into IMAGES (IMAGE_NAME, DESCRIPTION, USRID)
						values ("'.$_FILES["file"]["name"].'", "'.$_POST['description'].'", "'.$_SESSION["USRID"].'");');
					}
					else{
						$query = ('insert into IMAGES (IMAGE_NAME, USRID)
						values ("'.$_FILES["file"]["name"].'", "'.$_SESSION["USRID"].'");');
					}
					mysql_query($query);
					include('disconnect.php');
					header('Location:../index.php?page=image_upload');
				}
			}
		}
		else echo('Invalid file');
	}

	else{
		echo('	<form action="phplib/image_upload.php" method="post"
				enctype="multipart/form-data">
				<label for="file">Filename:</label>
				<input type="file" name="file" id="file" />
				<br />
				Decsription: <input type="text" name="description"/>
				<br/>
				<input type="submit" name="submit" value="Submit" />
				</form>
		');
	}
}
else echo('<br/><div>You cannot upload files as a guest. Please sign in to upload files.</div>');

?>